/*-------------------------------------------------------------------------
 *
 * pg_freespacemap.c
 *	  显示自由空间地图的内容
 *
 *	  contrib/pg_freespacemap/pg_freespacemap.c
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "access/relation.h"
#include "funcapi.h"
#include "storage/freespace.h"

PG_MODULE_MAGIC;

/*
 * 根据自由空间地图返回给定页面上的空闲空间数量。
 */
PG_FUNCTION_INFO_V1(pg_freespace);

Datum pg_freespace(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_blkno = PG_GETARG_INT64(1);
	int16		fc_freespace;
	Relation	fc_rel;

	fc_rel = relation_open(fc_relid, AccessShareLock);

	if (fc_blkno < 0 || fc_blkno > MaxBlockNumber)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid block number")));

	fc_freespace = GetRecordedFreeSpace(fc_rel, fc_blkno);

	relation_close(fc_rel, AccessShareLock);
	PG_RETURN_INT16(fc_freespace);
}
